<template>
  <div>
    <el-card class="el-card">
      <!--条件搜索-->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="账号" prop="username">
          <el-input
            placeholder="请输入账号"
            clearable
            size="default"
            v-model="queryParams.username"
          />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input
            placeholder="请输入昵称"
            clearable
            size="default"
            v-model="queryParams.nickname"
          />
        </el-form-item>
        <el-form-item label="管理员状态" prop="status">
          <el-select
            aria-placeholder="请选择管理员状态"
            size="default"
            v-model="queryParams.status"
          >
            <el-option
              v-for="item in StatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="beginTime">
          <el-date-picker
            size="default"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            v-model="queryParams.beginTime"
            placeholder="请选择开始时间"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            size="default"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            v-model="queryParams.endTime"
            placeholder="请选择结束时间"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="querySearch">
            <template #icon>
              <i-ep-search />
            </template>
            查询
          </el-button>
          <el-button @click="resetQueryForm">
            <template #icon>
              <i-ep-refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
      <!--操作按钮-->
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button
            v-if="hasPermission('api.sysAdmin.store')"
            plain
            type="primary"
            @click="handCreate"
          >
            <template #icon>
              <i-ep-plus />
            </template>
            新增
          </el-button>
        </el-col>
      </el-row>
      <!--列表-->
      <el-table
        border
        stripe
        class="w-full"
        header-cell-class-name="text-[#606266] !bg-[#eef1f6]"
        v-loading="tableData.loading"
        :data="tableData.data"
      >
        <template #empty>
          <el-empty :image-size="100" description="暂无数据" />
        </template>
        <el-table-column
          label="ID"
          header-align="center"
          v-if="false"
          prop="admin_id"
        />
        <el-table-column
          header-align="center"
          align="center"
          label="账号"
          prop="username"
        />
        <el-table-column
          header-align="center"
          align="center"
          label="昵称"
          prop="nickname"
        />
        <el-table-column
          header-align="center"
          align="center"
          label="手机号"
          prop="phone"
        />
        <el-table-column
          header-align="center"
          align="center"
          label="邮箱"
          prop="email"
        />
        <el-table-column
          header-align="center"
          align="center"
          label="头像"
          prop="profile_photo"
        >
          <template #default="scope">
            <el-avatar shape="circle" :src="scope.row.profile_photo" />
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          label="角色状态"
          align="center"
          prop="status"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              size="large"
              :inline-prompt="true"
              :active-value="1"
              :inactive-value="2"
              active-color="#13ce66"
              inactive-color="#f5222d"
              active-text="启用"
              inactive-text="停用"
              :before-change="() => handStateChange(scope.row)"
              :disabled="!hasPermission('api.sysAdmin.state')"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="center" label="部门/岗位">
          <template #default="scope">
            <div>{{ scope.row.dept_name }}/{{ scope.row.post_name }}</div>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="center" label="角色">
          <template #default="scope">
            <el-tag type="success">{{ scope.row.role_name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          label="创建时间"
          prop="create_time"
        />
        <el-table-column
          header-align="center"
          align="center"
          fixed="right"
          label="操作"
          width="290"
        >
          <template #default="scope">
            <el-button
              v-if="hasPermission('api.sysAdmin.show')"
              type="primary"
              class="!ml-0"
              text
              @click="handUpdate(scope.row)"
            >
              <template #icon>
                <i-ep-edit />
              </template>
              编辑
            </el-button>
            <el-button
              v-if="hasPermission('api.sysAdmin.destroy')"
              type="danger"
              class="!ml-0"
              text
              @click="handDestroy(scope.row)"
            >
              <template #icon><i-ep-delete /></template>
              删除
            </el-button>
            <el-button
              v-if="hasPermission('api.sysAdmin.restPassword')"
              type="success"
              class="!ml-0"
              text
              @click="handResetPassword(scope.row)"
            >
              <template #icon><i-ep-key /></template>
              重置密码
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <el-pagination
        class="justify-end"
        background
        @size-change="handleSizeChange()"
        @current-change="handleCurrentChange()"
        v-model:current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100, 500]"
        v-model:page-size="queryParams.pageSize"
        layout="total,sizes,prev,pager,next"
        :total="tableData.total"
        prev-text="上一页"
        next-text="下一页"
        :default-page-size="10"
        :pager-count="5"
      ></el-pagination>
    </el-card>
  </div>
  <AdminModel
    v-model:dialogVisible="dialogVisible"
    :admin_id="admin_id"
    @success="handSuccess"
  />
</template>

<script setup lang="ts">
import { reactive, onMounted, ref } from 'vue'
import { StatusList } from './admin.data'
import { AdminItem } from '@/api/auth/model/adminModel'
import { getList, state, destroy, resetPassword } from '@/api/auth/admin'
import { FormInstance } from 'element-plus'
import { useForm } from '@/hooks'
import AdminModel from './adminModel.vue'
import { usePermission } from '@/hooks/permission'

const queryFormRef = ref<FormInstance>(null!)

const { resetForm } = useForm()
const { hasPermission } = usePermission()

const dialogVisible = ref(false)
const admin_id = ref<number>(0)

//搜索参数
let queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  username: '',
  nickname: '',
  status: 0,
  beginTime: '',
  endTime: '',
})

//表格及分页数据
const tableData = reactive({
  loading: true,
  total: 0,
  data: [],
})

//获取列表数据
const getAdminList = async () => {
  try {
    const { code, data, message } = await getList(queryParams)
    if (code != 200) {
      ElMessage.error(message)
      return
    }
    tableData.total = data?.total || 0
    tableData.data = (data?.rows as never[]) || []
  } finally {
    tableData.loading = false
  }
}

//搜索
const querySearch = () => {
  getAdminList()
}
//搜索重置
const resetQueryForm = () => {
  resetForm(queryFormRef.value)
  getAdminList()
}

//page-size 改变时触发
const handleSizeChange = () => {
  getAdminList()
}

//current-page 改变时触发
const handleCurrentChange = () => {
  getAdminList()
}

//修改状态
const handStateChange = (row: AdminItem) => {
  return new Promise<boolean>((resolve, reject) => {
    try {
      let text = row.status === 1 ? '禁用' : '启用'
      ElMessageBox.confirm(`确定要${text}${row.username}账号吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { code, message } = await state({
            admin_id: row.admin_id,
            status: row.status == 1 ? 2 : 1,
          })
          if (code != 200) {
            ElMessage.error(`${text}${message}`)
            reject(false)
          }
          ElMessage.success(`${text}${message}`)
          resolve(true)
        })
        .catch(() => {
          ElMessage.info('取消修改')
          reject(false)
        })
    } catch (error) {
      reject(false)
    }
  })
}

//添加
const handCreate = () => {
  dialogVisible.value = true
  admin_id.value = 0
}

//更新
const handUpdate = (row: AdminItem) => {
  dialogVisible.value = true
  admin_id.value = row.admin_id
}

const handResetPassword = (row: AdminItem) => {
  ElMessageBox.prompt(`请输入${row.username}的新密码`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[^a-zA-Z0-9]).{6,18}/,
    inputErrorMessage: '密码中必须包含大小写字母、数字、特殊字符,长度6到18位',
  })
    .then(async ({ value }) => {
      const { code, message } = await resetPassword({
        admin_id: row.admin_id,
        password: value,
      })
      if (code != 200) {
        ElMessage.error(`重置${row.username}密码${message}`)
        return
      }
      ElMessage.success(`重置${row.username}密码${message}，新密码为：${value}`)
    })
    .catch(() => {
      ElMessage.info('取消重置密码')
    })
}

//添加/修改成功后執行
const handSuccess = () => {
  getAdminList()
}

//刪除
const handDestroy = async (row: AdminItem) => {
  ElMessageBox.confirm(`确定要删除${row.username}账号吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const { code, message } = await destroy({ admin_id: row.admin_id })
      if (code != 200) {
        ElMessage.error(`删除${row.username}${message}`)
        return
      }
      ElMessage.success(`删除${row.username}${message}`)
      getAdminList()
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })
}

onMounted(() => {
  getAdminList()
})
</script>

<style scoped></style>
